package com.pentofab.payrollmanagement.ui.controller;

import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

import com.pentofab.payrollmanagement.application.PayrollApplicationFactory;
import com.pentofab.payrollmanagement.dao.UserAccountsDao;
import com.pentofab.payrollmanagement.dao.impl.UserAccountsDaoImpl;
import com.pentofab.payrollmanagement.dao.model.Company;
import com.pentofab.payrollmanagement.dao.model.UserAccounts;
import com.pentofab.payrollmanagement.exception.BusinessException;
import com.pentofab.payrollmanagement.utilities.PayRollUtility;

public class ManageUserAccountsControler extends AbstractUIController  implements
Initializable, FormValidator{

	@FXML
	Parent root;
	@FXML
	private CheckBox addAtt;
	@FXML
	private CheckBox addUserAcc;
	@FXML
	private CheckBox addEmp;
	@FXML
	private CheckBox addLeave;
	@FXML
	private CheckBox addSal;
	@FXML
	private CheckBox modAtt;
	@FXML
	private CheckBox modEmp;
	@FXML
	private CheckBox modLeave;
	@FXML
	private CheckBox modSal;
	@FXML
	private CheckBox modUserAcc;
	@FXML
	private PasswordField passwordMain;
	@FXML
	private PasswordField passwordReEnter;
	@FXML
	private ChoiceBox<String> tillDate;
	@FXML
	private ChoiceBox<String> tillMonth;
	@FXML
	private ChoiceBox<String> tillYear;
	@FXML
	private TextField userNameField;
	@FXML
	private CheckBox viewAtt;
	@FXML
	private CheckBox viewEmp;
	@FXML
	private CheckBox viewLeave;
	@FXML
	private CheckBox viewSal;
	@FXML
	private CheckBox viewUserAcc;

	private ArrayList<String> tillMonthDaysList = new ArrayList<String>();
	private ArrayList<String> yearList = new ArrayList<String>();
	int maxDayOfmonth = -1;
	
	
	private static boolean add = false;
	
	public static void setAdd(boolean addTrue) {
		add = addTrue;
	}


	Company company = null;
	UserAccounts parentUser = null;
	UserAccounts currentUser = null;
	
	
	UserAccountsDao userAccountsDao = new UserAccountsDaoImpl();
	public void goBack() {

		if (getParent() != null && getParent().length() > 0) {
			PayrollApplicationFactory.getMainController().showScreen(
					getParent(), false);
		}
	}
	public void reset() {
		
		System.out.println("reset");
		refreshUI(company,parentUser);
	}
	public void save() {
		
		try {
		
		String validationMessage = getValidationMessage();
		if(!validationMessage.equals("")){
			showError(validationMessage);
			return;
		}
		
		String activeTillDate = tillDate.getSelectionModel()
				.getSelectedItem()
				+ "-"
				+ (tillMonth.getSelectionModel()
						.getSelectedIndex() + 1)
				+ "-"
				+ tillYear.getSelectionModel()
						.getSelectedItem();
		
		if(add){
			currentUser = new UserAccounts();
			String compCode = company.getCompanyID();
			String userName = userNameField.getText().trim();
			if(!userName.startsWith(compCode)){
				
			}
			currentUser.setUsername(userNameField.getText().trim());
			currentUser.setPassword(passwordMain.getText().trim());
			currentUser.setModificationdate("");
			currentUser.setModifiedby("");
			currentUser.setCreatedby(parentUser.getUsername());
			currentUser.setCreationdate(PayRollUtility.convertDateToString(new Date()));
		}else{
			currentUser.setModificationdate(PayRollUtility.convertDateToString(new Date()));
			currentUser.setModifiedby(parentUser.getUsername());

		}
		
		currentUser.setValidity(activeTillDate);
		currentUser.setPermissions(getPermission());
		
		if(add){
			userAccountsDao.createUserAccount(currentUser);
		}
		else{
			userAccountsDao.modifyUserAccount(currentUser,currentUser.getUsername());
		}
		} catch (BusinessException e) {
			showError(e.getMessage());
			moveFocusToComp(userNameField);
			return;
		}
		
		showInfo(String.format(UIMessages.SAVED_USER_ACCOUNT,userNameField.getText()));
		goBack();
	}

	@Override
	public void initialize(URL fxmlFileLocation, ResourceBundle resources) {

		tillYear.getSelectionModel().selectedIndexProperty()
				.addListener(new ChangeListener<Number>() {

					@Override
					public void changed(ObservableValue arg0, Number arg1,
							Number arg2) {

						tillMonth.getSelectionModel().clearSelection();
					}

				});
		tillMonth.getSelectionModel().selectedIndexProperty()
				.addListener(new ChangeListener<Number>() {

					@Override
					public void changed(ObservableValue arg0, Number arg1,
							Number arg2) {

						tillDate.getSelectionModel().clearSelection();
						tillDate.getItems().clear();
						tillMonthDaysList.clear();
						
						if(tillMonth.getSelectionModel().getSelectedIndex() < 0)
							return;
						
						maxDayOfmonth = PayRollUtility.getMaxDayofMonth(Integer
								.parseInt(tillYear.getSelectionModel()
										.getSelectedItem()), tillMonth
								.getSelectionModel().getSelectedIndex());

						for (int i = 1; i <= maxDayOfmonth; i++) {

							tillMonthDaysList.add(i + "");
						}
						tillDate.getItems().addAll(tillMonthDaysList);
					}

				});
	}

	@Override
	public Parent getView() {
		return root;
	}

	@Override
	public String getTitle() {
		return UIMessages.UITitles.USER_ACCOUNTS;
	}

	@Override
	public void refreshUI(Object... args) {
		
		String currentActiveTilleDate = null;
		
		if(!add){
			
			userNameField.setEditable(false);
			passwordMain.setEditable(false);
			passwordReEnter.setEditable(false);
			
		}
		
		if (args != null && args.length > 0) {
			Company company = (Company) args[0];
			this.company = company;
			
			
			if(args.length >1 && args[1] instanceof UserAccounts ){
				parentUser =(UserAccounts) args[1];
			}
			
			if(args.length >2 && args[2] instanceof UserAccounts ){
				currentUser =(UserAccounts) args[2];
				System.out.println(" currentUser : "+currentUser);
				userNameField.setText(currentUser.getUsername());
				userNameField.setEditable(false);
				
				
				passwordMain.setText(currentUser.getPassword());
				passwordMain.setEditable(false);
				
				passwordReEnter.setText(currentUser.getPassword());
				passwordReEnter.setEditable(false);
				currentActiveTilleDate =currentUser.getValidity();
				
			}
		}
		
		String currentUserPer = null;
		if(currentUser != null){
			currentUserPer = currentUser.getPermissions();
		}
		
		
		if(add){
			
			userNameField.setEditable(true);
			passwordMain.setEditable(true);
			passwordReEnter.setEditable(true);
		}
		if(add || (args != null && args.length < 2)){
			userNameField.clear();
			passwordMain.clear();
			passwordReEnter.clear();
			}
		tillYear.getItems().clear();
		yearList.clear();
		int year = PayRollUtility.getYear();
		for (int i = 0; i < 10; i++) {
			yearList.add(year + "");
			year++;
		}
		year = PayRollUtility.getYear();
		tillYear.getItems().addAll(yearList);
		
		//Rest check boxes Attendance
		addAtt.setSelected(false);
		modAtt.setSelected(false);
		viewAtt.setSelected(false);

		//Rest check boxes Attendance
		addLeave.setSelected(false);
		modLeave.setSelected(false);
		viewLeave.setSelected(false);

		//Rest check boxes Employee
		addEmp.setSelected(false);
		modEmp.setSelected(false);
		viewEmp.setSelected(false);
		
		//Rest check boxes Attendance
		addSal.setSelected(false);
		modSal.setSelected(false);
		viewSal.setSelected(false);

		//Rest check boxes Attendance
		addUserAcc.setSelected(false);
		modUserAcc.setSelected(false);
		viewUserAcc.setSelected(false);
		
		tillDate.getSelectionModel().clearSelection();
		tillMonth.getSelectionModel().clearSelection();
		tillDate.getSelectionModel().clearSelection();
		
		if(currentActiveTilleDate != null){
		String[] date = currentActiveTilleDate.split("-");
		System.out.println("currentActiveTilleDate : "+currentActiveTilleDate+" ; "+date[0]+" - "+date[1]+" - "+date[2] );
		tillYear.getSelectionModel().select(date[2]);
		tillMonth.getSelectionModel().select(Integer.parseInt(date[1]));
		tillDate.getSelectionModel().select(Integer.parseInt(date[0]));
		}
		
		setPermission( currentUserPer, parentUser.getPermissions());
	}
	@Override
	public boolean isValid() {
		return false;
	}
	@Override
	public String getValidationMessage() {
		
		String userName = userNameField.getText().trim();
		String passwodMain = passwordMain.getText();
		String confirmPassword = passwordReEnter.getText().trim();
		if(userName.equals("")){
			return UIMessages.USER_NAME_EMPTY;
		}
		if(userName.length() <5 ){
			return UIMessages.USER_NAME_LENGHT;
		}
		if(passwodMain.equals("")){
			return UIMessages.PRIMARY_PASSWORD_EMPTY;
		}
		if(passwodMain.length() <6 ){
			return UIMessages.PASSWORD_FIELD_LENGHT;
		}
		if(confirmPassword.equals("")){
			return UIMessages.PASSWORD_RETYPE_FIELD_EMPTY;
		}
		if(!passwodMain.equals(confirmPassword)){
			return UIMessages.PASSWORDS_NOT_EQUAL;
		}
		if(tillYear.getSelectionModel().getSelectedIndex() < 0){
			return UIMessages.till_uear;
		}
		if(tillMonth.getSelectionModel().getSelectedIndex() < 0){
			return UIMessages.till_month;
		}
		if(tillDate.getSelectionModel().getSelectedIndex() < 0){
			return UIMessages.till_date;
		}
		
		return "";
	}
	

	private String getPermission() {

		StringBuffer permission = new StringBuffer();

		// Attendance
		if (addAtt.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (viewAtt.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (modAtt.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		// Leave
		if (addLeave.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (viewLeave.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (modLeave.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		// Employee
		if (addEmp.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (viewEmp.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (modEmp.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}
		
		//Salary
		if (addSal.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (viewSal.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (modSal.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}
		
		//User accounts
		if (addUserAcc.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (viewUserAcc.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		if (modUserAcc.isSelected()) {
			permission.append("1");
		} else {
			permission.append("0");
		}

		return permission.toString();
	}
	
	private void setPermission(String permission, String parentPermission) {

		System.out.println("parentPermission : "+parentPermission);
		System.out.println("permission : "+permission);
		
		if(permission == null){
			permission = UIMessages.UIPermission.DEFAULT;
		}else{
			PayRollUtility.debug("User permission : "+permission);
		}
		// Attendance
		if (parentPermission.charAt(UIMessages.UIPermission.ATT_ADD) == '0') {
			addAtt.setDisable(true);
		} 
		
		System.out.println("permission.charAt(UIMessages.UIPermission.ATT_ADD) : "+permission.charAt(UIMessages.UIPermission.ATT_ADD));
		System.out.println(permission.charAt(UIMessages.UIPermission.ATT_ADD) == '1');
		if (permission.charAt(UIMessages.UIPermission.ATT_ADD) == '1') {
			addAtt.setSelected(true);
		}

		if (parentPermission.charAt(UIMessages.UIPermission.ATT_VIEW) == '0') {
			viewAtt.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.ATT_VIEW) == '1') {
			viewAtt.setSelected(true);
		}

		if (parentPermission.charAt(UIMessages.UIPermission.ATT_MOD) == '0') {
			modAtt.setDisable(true);
		}else if (permission.charAt(UIMessages.UIPermission.ATT_MOD) == '1') {
			modAtt.setSelected(true);
		}
			// Leave
		if (parentPermission.charAt(UIMessages.UIPermission.LEAVE_ADD) == '0') {
			addLeave.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.LEAVE_ADD) == '1') {
			addLeave.setSelected(true);
		}

		if (parentPermission.charAt(UIMessages.UIPermission.LEAVE_VIEW) == '0') {
			viewLeave.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.LEAVE_VIEW) == '1') {
			viewLeave.setSelected(true);
		}

		if (parentPermission.charAt(UIMessages.UIPermission.LEAVE_MOD) == '0') {
			modLeave.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.LEAVE_MOD) == '1') {
			modLeave.setSelected(true);
		}

		// Employee
		if (parentPermission.charAt(UIMessages.UIPermission.EMP_ADD) == '0') {
			addEmp.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.EMP_ADD) == '1') {
			addEmp.setSelected(true);
		}

		if (parentPermission.charAt(UIMessages.UIPermission.EMP_VIEW) == '0') {
			viewEmp.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.EMP_VIEW) == '1') {
			viewEmp.setSelected(true);
		}

		if (parentPermission.charAt(UIMessages.UIPermission.EMP_MOD) == '0') {
			modEmp.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.EMP_MOD) == '1') {
			modEmp.setSelected(true);
		}
		
		//Salary
		if (parentPermission.charAt(UIMessages.UIPermission.SAL_ADD) == '0') {
			addSal.setDisable(true);
		}else if (permission.charAt(UIMessages.UIPermission.SAL_ADD) == '1') {
			addSal.setSelected(true);
		}

		if (parentPermission.charAt(UIMessages.UIPermission.SAL_VIEW) == '0') {
			viewSal.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.SAL_VIEW) == '1') {
			viewSal.setSelected(true);
		}
		if (parentPermission.charAt(UIMessages.UIPermission.SAL_MOD) == '0') {
			modSal.setDisable(true);
		} 
		if (permission.charAt(UIMessages.UIPermission.SAL_MOD) == '1') {
			modSal.setSelected(true);
		} 
		
		//User accounts
		if (parentPermission.charAt(UIMessages.UIPermission.USER_ADD) == '0') {
			addUserAcc.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.USER_ADD) == '1') {
			addUserAcc.setSelected(true);
		}
		if (parentPermission.charAt(UIMessages.UIPermission.USER_VIEW) == '0') {
			viewUserAcc.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.USER_VIEW) == '1') {
			viewUserAcc.setSelected(true);
		}
		if (parentPermission.charAt(UIMessages.UIPermission.USER_MOD) == '0') {
			modUserAcc.setDisable(true);
		}
		if (permission.charAt(UIMessages.UIPermission.USER_MOD) == '1') {
			modUserAcc.setSelected(true);
		}
	}
}
